<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/17
 * Time: 10:54
 * Function:
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Platform\System\Tools\ResultTool;

class CheckPermission
{
    /**
     * @param Request $request
     * @param Closure $next
     * @param $guard
     * @return mixed
     */
    public function handle(Request $request, Closure $next,$guard)
    {
        $method = $request->method();
        $uri = $request->route()->uri();

        if (!$this->check($method, $uri, $guard)) {
            // TODO:验证后操作
            myResult()->stop(ResultTool::CODE_NO_RIGHT);
        }

        return $next($request);
    }

    /**
     * @param $method
     * @param $uri
     * @param $guard
     * @return bool
     */
    protected function check($method, $uri, $guard)
    {
        $user = auth($guard)->user();

        if ($user->isAdmin()) {
            return true;
        }
        $permissions = $user->getPermissions();
        if (!empty($permissions[$method])){
            return in_array($uri, $permissions[$method]);
        }else return false;

    }
}